/**
 * 
 */
package org.tigris.elfin;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author zhisen.huang
 * 
 */
public abstract class VariableContainer {

	public static HashMap<String, Object> variables = new HashMap<String, Object>();

	public static void assign(String name, Object value) {
		variables.put(name, value);
	}

	public static void assign(Map<String, Object> params) {
		variables.putAll(params);
	}

	public static String getValue(String name) {
		int dot = name.lastIndexOf('.');
		String propertyName;
		String objectName;
		Object object;

		if (dot > 0) {
			objectName = name.substring(0, dot);
			propertyName = name.substring(dot + 1, name.length());
		} else {
			return String.valueOf(variables.get(name));
		}
		try {
			Class[] params = new Class[] {};
			String getter = "get"
					+ Character.toUpperCase(propertyName.charAt(0))
					+ propertyName.substring(1, propertyName.length());
			object = variables.get(objectName);
			
			Method method = object.getClass().getMethod(getter, params);
			return String.valueOf(method.invoke(object, new Object[] {}));
		} catch (NoSuchMethodException ex) {
			ex.printStackTrace();
		} catch (IllegalAccessException ex) {
			ex.printStackTrace();
		} catch (InvocationTargetException ex) {
			ex.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "0";
	}
}
